package com.example.moshudriver.fragment;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.BeeFramework.Utils.Utils;
import com.BeeFramework.model.BusinessResponse;
import com.BeeFramework.view.RoundedWebImageView;
import com.sgr.dykdriver.R;
import com.example.moshudriver.activity.F0_ProfileActivity;
import com.example.moshudriver.activity.SlidingActivity;
import com.example.moshudriver.model.MessageUnreadCountModel;
import com.example.moshudriver.model.UserBalanceModel;
import com.example.moshudriver.protocol.ApiInterface;
import com.example.moshudriver.protocol.USER;
import com.example.moshudriver.tools.MessageConstant;
import com.example.moshudriver.tools.O2OMobile;
import com.example.moshudriver.tools.O2OMobileAppConst;
import com.external.androidquery.callback.AjaxStatus;
import com.external.eventbus.EventBus;
import com.nostra13.universalimageloader.core.ImageLoader;

public class A2_MenuFragment extends Fragment implements OnClickListener,
		BusinessResponse {
	private static final String TAG = "A2_MenuFragment";

	// private A0_HomeFragment mA0HomeFragment;
	private A1_HomeFragment mA1HomeFragment;

	private MyBalanceFragment mMyBalanceFragment;
	private H0_MessageFragment mH0MessageFragment;
	private F4_RefferalFragment mRefferalFragment;
	private SettingFragment mSettingFragment;
	private E0_PublishedOrdersFragment mMyOrderListFragment;

	private View mHeaderView;
	private ListView mListView;

	private RoundedWebImageView mAvatar;
	private TextView mUserName;
	private TextView mMobile;
	private LinearLayout mHome;
	private LinearLayout mTravel;
	private LinearLayout mMessage;
	private TextView mMessageNum;
	private LinearLayout mInvite;
	private SharedPreferences mShared;
	private UserBalanceModel mUserBalance;
	private MessageUnreadCountModel mMessageUnreadCountModel;
	private UserBalanceModel mUserBalanceModel;
	private USER mUser;
	protected ImageLoader publicImageLoader = ImageLoader.getInstance();

	public int publucLastSelectedMenu = -1;
	public static int publicMessageUnreadCount = 0;
	private LinearLayout mPurse;
	private LinearLayout mSetting;
	private LinearLayout mGuider;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.a2_menu, null);
		mHeaderView = inflater.inflate(R.layout.a2_menu_header, null);
		mListView = (ListView) view.findViewById(R.id.menu_listview);

		mGuider = (LinearLayout) mHeaderView.findViewById(R.id.left_guider);
		mAvatar = (RoundedWebImageView) mHeaderView
				.findViewById(R.id.left_avatar);

		mUserName = (TextView) mHeaderView.findViewById(R.id.left_userName);
		mMobile = (TextView) mHeaderView.findViewById(R.id.left_phone);

		mHome = (LinearLayout) mHeaderView.findViewById(R.id.left_home);

		mPurse = (LinearLayout) mHeaderView.findViewById(R.id.left_purse);

		mTravel = (LinearLayout) mHeaderView.findViewById(R.id.left_travel);

		mMessage = (LinearLayout) mHeaderView.findViewById(R.id.left_message);
		mMessageNum = (TextView) mHeaderView
				.findViewById(R.id.left_message_num);

		mInvite = (LinearLayout) mHeaderView.findViewById(R.id.left_invite);

		mSetting = (LinearLayout) mHeaderView.findViewById(R.id.left_setting);

		mListView.addHeaderView(mHeaderView);
		mListView.setAdapter(null);
		view.setOnClickListener(this);
		mUserBalance = new UserBalanceModel(getActivity());
		mUserBalance.addResponseListener(this);

		mUserBalance.get();

		mShared = getActivity().getSharedPreferences(
				O2OMobileAppConst.USERINFO, 0);
		String userStr = mShared.getString("user", "");
		try {
			if (userStr != null) {
				JSONObject userJson = new JSONObject(userStr);
				USER user = new USER();
				user.fromJson(userJson);
				String phone = user.mobile_phone;
				if (phone!=null&&phone.length()==11) {
					mMobile.setText(phone.substring(0, 3) + "****"
							+ phone.substring(7, phone.length()));
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		mMessageUnreadCountModel = new MessageUnreadCountModel(getActivity());
		mMessageUnreadCountModel.addResponseListener(this);

		mUserBalanceModel = new UserBalanceModel(getActivity());
		mUserBalanceModel.addResponseListener(this);

		if (!EventBus.getDefault().isregister(this)) {
			EventBus.getDefault().register(this);
		}

		return view;
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		publucLastSelectedMenu = mHome.getId();
		mHome.setOnClickListener(this);
		mPurse.setOnClickListener(this);
		mTravel.setOnClickListener(this);
		mMessage.setOnClickListener(this);
		mInvite.setOnClickListener(this);
		mSetting.setOnClickListener(this);
		mGuider.setOnClickListener(this);
	}

	public void switchFragment(Fragment fragment, boolean showLeft) {
		if (getActivity() == null)
			return;
		if (getActivity() instanceof SlidingActivity) {
			SlidingActivity slidingActivity = (SlidingActivity) getActivity();
			slidingActivity.switchContent(fragment);
			if (showLeft) {
				slidingActivity.isShowLeft(true);
				slidingActivity.showLeft();
			}
		}
	}

	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		// TODO Auto-generated method stub
		if (url.endsWith(ApiInterface.MESSAGE_UNREAD_COUNT)) {
			publicMessageUnreadCount = mMessageUnreadCountModel.publicUnreadCount;
			setMessageUnreadCount();
		} else if (url.endsWith(ApiInterface.USER_PROFILE)) {
			String userStr = mShared.getString("user", "");
			try {
				if (userStr != null) {
					JSONObject userJson = new JSONObject(userStr);
					mUser = new USER();
					mUser.fromJson(userJson);
					publicImageLoader.displayImage(mUser.avatar.thumb, mAvatar,
							O2OMobile.options_head);
					String username = Utils.replaceBlank(mUser.nickname);
					if (username.length() < 8) {

						mUserName.setText(username.substring(0, 2)
								+ "*"
								+ username.subSequence(username.length() - 2,
										username.length()));
					} else {
						mUserName.setText(username);
					}

				}
			} catch (Exception e) {

			}
		}
	}

	private void setMessageUnreadCount() {
		if (publicMessageUnreadCount <= 0) {
			mMessageNum.setVisibility(View.GONE);
		} else {
			mMessageNum.setVisibility(View.VISIBLE);
			if (publicMessageUnreadCount < 100) {
				mMessageNum.setText(publicMessageUnreadCount + "");
			} else {
				mMessageNum.setText("99+");
			}
		}
	}

	public void onEvent(Object event) {
		Message message = (Message) event;
		if (message.what == MessageConstant.MESSAGE_READ) {
			publicMessageUnreadCount = publicMessageUnreadCount - 1;
			setMessageUnreadCount();
		} else if (message.what == MessageConstant.APPLY_FREEMAN) {
			mUserBalanceModel.getProfile(mUser.id);
			// switchFragment(mA0HomeFragment, true);
			switchFragment(mA1HomeFragment, true);
		} else if (message.what == MessageConstant.SIGN_IN_SUCCESS) {
			mMessageUnreadCountModel.getMessageUnreadCount();
		}
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		if (EventBus.getDefault().isregister(this)) {
			EventBus.getDefault().unregister(this);
		}
		super.onDestroyView();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mUserBalance.get();
		mMessageUnreadCountModel.getMessageUnreadCount();

		mShared = getActivity().getSharedPreferences(
				O2OMobileAppConst.USERINFO, 0);
		String userStr = mShared.getString("user", "");
		try {
			if (userStr != null) {
				JSONObject userJson = new JSONObject(userStr);
				mUser = new USER();
				mUser.fromJson(userJson);
				publicImageLoader.displayImage(mUser.avatar.thumb, mAvatar,
						O2OMobile.options_head);
				mUserName.setText(Utils.replaceBlank(mUser.nickname));

			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.left_home:
			if (publucLastSelectedMenu == R.id.left_home) {
				if (getActivity() instanceof SlidingActivity) {
					SlidingActivity slidingActivity = (SlidingActivity) getActivity();
					slidingActivity.showLeft();
				}
			} else {
				// mA0HomeFragment = new A0_HomeFragment();
				// switchFragment((Fragment) mA0HomeFragment, true);
				mA1HomeFragment = new A1_HomeFragment();
				switchFragment((Fragment) mA1HomeFragment, true);
			}
			break;

		case R.id.left_purse:
			if (publucLastSelectedMenu == R.id.left_purse) {
				if (getActivity() instanceof SlidingActivity) {
					SlidingActivity slidingActivity = (SlidingActivity) getActivity();
					slidingActivity.showLeft();
				}
			} else {
				mMyBalanceFragment = new MyBalanceFragment();
				switchFragment((Fragment) mMyBalanceFragment, true);

			}
			break;
		case R.id.left_message:
			if (publucLastSelectedMenu == R.id.left_message) {
				if (getActivity() instanceof SlidingActivity) {
					SlidingActivity slidingActivity = (SlidingActivity) getActivity();
					slidingActivity.showLeft();
				}
			} else {
				mH0MessageFragment = new H0_MessageFragment();
				switchFragment((Fragment) mH0MessageFragment, true);

			}
			break;
		case R.id.left_invite:
			if (publucLastSelectedMenu == R.id.left_invite) {
				if (getActivity() instanceof SlidingActivity) {
					SlidingActivity slidingActivity = (SlidingActivity) getActivity();
					slidingActivity.showLeft();
				}
			} else {
				mRefferalFragment = new F4_RefferalFragment();
				switchFragment((Fragment) mRefferalFragment, true);
			}
			break;
		// 设置
		case R.id.left_setting:
			if (publucLastSelectedMenu == R.id.left_setting) {
				if (getActivity() instanceof SlidingActivity) {
					SlidingActivity slidingActivity = (SlidingActivity) getActivity();
					slidingActivity.showLeft();
				}
			} else {
				mSettingFragment = new SettingFragment();
				switchFragment((Fragment) mSettingFragment, true);
			}
			break;
		case R.id.left_travel:
			if (publucLastSelectedMenu == R.id.left_travel) {
				if (getActivity() instanceof SlidingActivity) {
					SlidingActivity slidingActivity = (SlidingActivity) getActivity();
					slidingActivity.showLeft();
					// slidingActivity.sho
				}
			} else {
				mMyOrderListFragment = new E0_PublishedOrdersFragment();
				switchFragment((Fragment) mMyOrderListFragment, true);
			}
			break;
		case R.id.left_guider:
			Intent intent_profile = new Intent(getActivity(),
					F0_ProfileActivity.class);
			intent_profile.putExtra(F0_ProfileActivity.USER_ID, mUser.id);
			startActivity(intent_profile);
			getActivity().overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
			break;

		}
		publucLastSelectedMenu = v.getId();
	}

}
